using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;

public class AudioUtils {



  public static AudioClip CreateFromOgg(byte[] bytes, string clipName = "oggClip") {
    using (var ms = new MemoryStream(bytes))
    using (var vorbisReader = new NVorbis.VorbisReader(ms, true)) {
      // 获取音频信息
      int channels = vorbisReader.Channels;
      int sampleRate = vorbisReader.SampleRate;
      int totalSamples = (int)(vorbisReader.TotalSamples * channels);

      // 创建缓冲区
      float[] audioData = new float[totalSamples];

      // 读取所有样本数据
      int samplesRead = vorbisReader.ReadSamples(audioData, 0, totalSamples);

      // 创建Unity的AudioClip
      AudioClip clip = AudioClip.Create(
          clipName,
          samplesRead / channels,
          channels,
          sampleRate,
          false
      );

      // 设置音频数据
      clip.SetData(audioData, 0);
      return clip;
    }
  }


  // WAV文件头结构
  private struct WavHeader {
    public int chunkID;       // "RIFF"
    public int fileSize;      // 文件总大小-8
    public int riffType;      // "WAVE"
    public int fmtID;         // "fmt "
    public int fmtSize;       // fmt块大小(16或18)
    public short fmtTag;      // 格式标签(1=PCM)
    public short channels;     // 声道数
    public int sampleRate;    // 采样率
    public int byteRate;      // 每秒字节数
    public short blockAlign;   // 数据块对齐单位
    public short bitDepth;    // 位深度(8,16,24,32)
    public int dataID;        // "data"
    public int dataSize;      // 音频数据大小
  }

  public static AudioClip CreateFromWav(byte[] wavBytes, string clipName = "wavClip") {
    using (var memStream = new MemoryStream(wavBytes))
    using (var reader = new BinaryReader(memStream)) {
      // 读取WAV头信息
      WavHeader header = new WavHeader {
        chunkID = reader.ReadInt32(),
        fileSize = reader.ReadInt32(),
        riffType = reader.ReadInt32(),
        fmtID = reader.ReadInt32(),
        fmtSize = reader.ReadInt32(),
        fmtTag = reader.ReadInt16(),
        channels = reader.ReadInt16(),
        sampleRate = reader.ReadInt32(),
        byteRate = reader.ReadInt32(),
        blockAlign = reader.ReadInt16(),
        bitDepth = reader.ReadInt16()
      };

      // 检查是否是有效的WAV文件
      if (header.chunkID != 0x46464952) // "RIFF"
        throw new FormatException("不是有效的WAV文件");

      // 跳过可能的扩展信息
      if (header.fmtSize > 16)
        reader.BaseStream.Seek(header.fmtSize - 16, SeekOrigin.Current);

      // 查找data块
      while (reader.BaseStream.Position < reader.BaseStream.Length) {
        int chunkID = reader.ReadInt32();
        int chunkSize = reader.ReadInt32();

        if (chunkID == 0x61746164) // "data"
        {
          // 读取音频数据
          byte[] dataBytes = reader.ReadBytes(chunkSize);

          // 转换为float数组
          float[] samples = ConvertByteToFloat(dataBytes, header.bitDepth);

          // 创建AudioClip
          AudioClip clip = AudioClip.Create(
              clipName,
              samples.Length / header.channels,
              header.channels,
              header.sampleRate,
              false
          );

          clip.SetData(samples, 0);
          return clip;
        } else {
          // 跳过其他块
          reader.BaseStream.Seek(chunkSize, SeekOrigin.Current);
        }
      }

      throw new FormatException("WAV文件中未找到音频数据");
    }
  }

  private static float[] ConvertByteToFloat(byte[] bytes, int bitDepth) {
    int sampleCount = bitDepth == 8 ? bytes.Length : bytes.Length / 2;
    float[] samples = new float[sampleCount];

    if (bitDepth == 8) {
      // 8位PCM: 无符号0-255，转换为-1到1
      for (int i = 0; i < bytes.Length; i++) {
        samples[i] = (bytes[i] - 128) / 128f;
      }
    } else if (bitDepth == 16) {
      // 16位PCM: 有符号short，转换为-1到1
      for (int i = 0; i < bytes.Length; i += 2) {
        short sample = BitConverter.ToInt16(bytes, i);
        samples[i / 2] = sample / 32768f;
      }
    } else if (bitDepth == 24) {
      // 24位PCM: 转换为32位float
      for (int i = 0; i < bytes.Length; i += 3) {
        // 将24位转换为32位
        int sample = (bytes[i] << 8) | (bytes[i + 1] << 16) | (bytes[i + 2] << 24);
        samples[i / 3] = sample / 2147483648f;
      }
    } else if (bitDepth == 32) {
      // 32位PCM或float: 直接转换
      for (int i = 0; i < bytes.Length; i += 4) {
        samples[i / 4] = BitConverter.ToSingle(bytes, i);
      }
    } else {
      throw new NotSupportedException($"不支持的位深度: {bitDepth}");
    }

    return samples;
  }

}